package com.we.wfc.common.config;

import com.google.common.base.Predicate;
import com.we.wfc.common.constants.BaseConstants;
import com.we.wfc.common.properties.SwaggerProp;
import lombok.AllArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.ApiKeyVehicle;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Arrays;

/**
 * @Description: Swagger From BootStrap配置相关
 * @Author: Liangzy(Feeling)
 * @Date:Create in 2019-08-05 19:14
 */
@Configuration
@EnableSwagger2
@AllArgsConstructor
@EnableConfigurationProperties(SwaggerProp.class)
public class SwaggerConfiguration {

    private final SwaggerProp swaggerProp;

    @Bean
    public Docket createRestApi() {
        Predicate<String> selector = PathSelectors.none();
        if (swaggerProp.isEnable()) {
            selector = PathSelectors.any();
        }
        return new Docket(DocumentationType.SWAGGER_2)
                .securitySchemes(Arrays.asList(new ApiKey(BaseConstants.SWAGGER_AUTHORIZATION_ID, "Authorization", ApiKeyVehicle.HEADER.getValue())))
                .host(swaggerProp.getHost())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.we"))
                .paths(selector)
                .build()
                .apiInfo(apiInfo())
                .enable(swaggerProp.isEnable());
    }

    private ApiInfo apiInfo() {
        if (swaggerProp.isEnable()) {
            return new ApiInfoBuilder()
                    .title(swaggerProp.getTitle())
                    .description(swaggerProp.getDescription())
                    .contact(new Contact(swaggerProp.getAuthor(), "http://shade.fun", swaggerProp.getEmail()))
                    .termsOfServiceUrl(swaggerProp.getServiceUrl())
                    .version(swaggerProp.getVersion())
                    .build();
        }
        return ApiInfo.DEFAULT;
    }

}